package com.example.config;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Properties;

/**
 * @description:
 * @author: zsw
 * @time: 2021/9/1 9:51
 */
@Intercepts(
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
)
@Component
public class Myplugin implements Interceptor {


    //获取到拦截的对象，底层也是通过代理来实现的，实际上是拿到一个目标的代理对象
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    //获取配置文件中设置的阈值等参数
    @Override
    public void setProperties(Properties properties) {

    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        //获取操作类型，crud
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //获取参数
        Object parameter = invocation.getArgs()[1];
        Field[] fields = parameter.getClass().getDeclaredFields();


        for (Field field : fields) {
            //注入对应的属性值
            if (SqlCommandType.INSERT.equals(sqlCommandType)){
                if (field.getName().equals("createTime") ) {
                    field.setAccessible(true);
                    field.set(parameter, LocalDateTime.now());
                }
                if (field.getName().equals("updateTime") ){
                    field.setAccessible(true);
                    field.set(parameter, LocalDateTime.now());
                }
            }
            if (field.getName().equals("updateTime") && SqlCommandType.UPDATE.equals(sqlCommandType)) {
                field.setAccessible(true);
                field.set(parameter, LocalDateTime.now());
            }
        }
        Object object = invocation.proceed();

        return object;
    }


}
